<template>
  <div class="bgc-fff">
    <el-card class="fexd">
      <el-input :placeholder="$route.query.roleName" size="small"> </el-input>
      <br />
      <br />
      <el-button type="primary" size="small" @click="doAssign">保存</el-button>
      <el-button size="small" @click="$router.replace('/acl/role/list')">
        取消
      </el-button>
    </el-card>
    <el-card>
      <el-tree
        @check="checkHandle"
        :data="permissionList.children"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="{ children: 'children', label: 'name' }"
        ref="treeRef"
      ></el-tree>
    </el-card>
  </div>
</template>

<script>
import { toAssignApi, doAssignApi } from '@/api/acl/authApi'
export default {
  name: 'Auth',
  data() {
    return {
      permissionList: {},
      assignIdList: [],
      halfCheckedKeys: []
    }
  },
  mounted() {
    const { id, roleName } = this.$route.query
    this.getPermission(id, roleName)
  },
  methods: {
    // 保存
    async doAssign() {
      const { id } = this.$route.query
      this.halfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()
      const idList = [...this.assignIdList, ...this.halfCheckedKeys]
      await doAssignApi(id, idList)
      this.$message.success('保存成功')
      this.$router.replace('/acl/role/list')
    },

    // 选中节点
    checkHandle(data, { checkedKeys }) {
      this.assignIdList = checkedKeys
    },
    // 封装请求数据的方法
    async getPermission(id, roleName) {
      const { data } = await toAssignApi(id, roleName)
      this.permissionList = data
      this.assignIdList = this.getCheckedIdList(data.children)
      this.$refs.treeRef.setCheckedKeys(this.assignIdList, true)
    },
    // 封装获取选中id列表的方法
    getCheckedIdList(list) {
      let arr = []
      list.forEach((item) => {
        if (item.children?.length) {
          const childArr = this.getCheckedIdList(item.children)
          if (childArr.length === item.children.length) {
            arr.push(item.id)
          }
          arr = [...arr, ...childArr]
        } else {
          if (item.select) {
            arr.push(item.id)
          }
        }
      })
      return arr
    }
  }
}
</script>

<style scoped>
.fexd {
  position: sticky;
  top: 0;
  z-index: 123;
  margin-bottom: 10px;
}
.bgc-fff {
  background-color: #fff;
}
</style>
